﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
//using PSE.ProcessManager.Common.Logging;
using System.IO;
using System.Configuration;
using System.Reflection;
using System.Threading;
using PSE.ProcessManager.Server.InteligenceManagerInstance;
using PSE.ProcessManager.Entity;
using System.ServiceModel;
using System.Net;
using PSE.ProcessManager.ResourceAccess;
using PSE.ProcessManager.Server.InteligenceManager.Configuration;
using PSE.ProcessManager.Common.Gateway;
using PSE.ProcessManager.Common.Process;

namespace PSE.ProcessManager.Server.InteligenceManager
{
    public partial class InteligenceManager : ServiceBase
    {
        private ServiceHost _hoster;
        private InteligenceManagerService _inteligenceManagerService;

        public InteligenceManager()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            bool startAll = true;

            if (args.Length == 1)
                Boolean.TryParse(args[0], out startAll);

            PSE.LogPackager.Service.LogPackagerServiceHost.Start(PSE.Framework.Configuration.Components.SystemComponents.Process);

            //iniciar o hosteamento do servico do inteligence manager
            StartInteligenceManagerService();

            if (startAll)
            {
                //recuperar as configuracoes de produtos com processos hospedados pelo process manager 
                ProductConfigurationSection productConfig = System.Configuration.ConfigurationManager.GetSection("productConfiguration") as ProductConfigurationSection;

                if (productConfig != null)
                {
                    foreach (ProductConfigurationElement p in productConfig.Products)
                    {
                        _inteligenceManagerService.StartProduct(p.Id);
                    }
                }
                else
                {
                    throw new ConfigurationErrorsException("The configuration section 'productConfiguration' was not found.");
                }
            }
        }

        protected override void OnStop()
        {
            if (_hoster != null)
            {
                _hoster.Close();
            }

            if (_inteligenceManagerService != null)
            {
                _inteligenceManagerService.Dispose();
            }

            PSE.LogPackager.Service.LogPackagerServiceHost.Stop();
        }

        private void StartInteligenceManagerService()
        {
            _inteligenceManagerService = new InteligenceManagerService();
            _hoster = new ServiceHost(_inteligenceManagerService);
            _hoster.Open();
        }
    }
}
